<?php

namespace Admin\Controller;

class MenuController extends PublicController
{
    function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $result = M("Menu")->select();
        foreach ($result as $key=>$value){
            $menu_id=$value['id'];
            $result[$key]['menu_count']= M('good')->where("menu_id='$menu_id'")->count();
        }
        $this->assign("menulist", $result);
        $this->display();
    }

    public function edit()
    {
        //根据id查询
        $id = I('get.id');
        if($id){
            $result = M("Menu")->where("id = '$id'")->find();
        }else{
            $result ='';
        }
        $this->assign("menulist", $result);
        $this->display();
    }

    /**
     * 增加/编辑 商品分类信息
     */
    public function addmenu(){
        $name = I("post.name");
        $id = I("post.id");
        //是否有图片上传
//        if ($_FILES['icon']['name'] !== '') {
//            $upload = $this->uploadOne($_FILES['icon']);
//            $icon = ltrim($upload[savepath], ".").$upload[savename];
//        }else{
//            $icon = I("post.icon");
//        }

        if($id){
            //编辑分类信息
            $data['name'] = $name;
            $data['id'] = $id;
//            $data['icon'] = $icon;
            $result = M("Menu")->save($data);
        }else{
            //增加分类信息
            $data['name'] = $name;
//            $data['icon'] = $icon;
            //查询分类名是否重复
            $menuInfo = M("Menu")->where("name = '$name'")->find();
            if($menuInfo){
                $this->error('分类名不能相同！');
            }else{
                $result = M("Menu")->add($data);
            }
        }

        if($result !== false ){
            $this->success("操作成功", U("Menu/index"));
        }else{
            $this->error("操作失败");
        }
    }

    /**
     * 删除商品分类
     */
    public function delMenu(){
        $id = I("get.id");
        $result = M("Menu")->where(array(
            'id' => $id
        ))->delete();

        if($result !== false){
            $this->success("删除成功");
        }else{
            $this->error("操作失败");
        }
    }

}